const router = require('koa-router')()
const uploader = require('../uploader')
const mongoose = require('mongoose')
const path = require('path')
const fs = require('fs')
const util = require('util')
const stats = require('../helpers/stats')
const popular = require('../helpers/popular')
const comments = require('../helpers/comments')
const md5 = require('MD5')
const timeago = require("timeago.js")()

const rename = util.promisify(fs.rename)
const unlink = util.promisify(fs.unlink)

router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.post('/:imageid/comment', async function (ctx, next) {
  let user = ctx.currentUser;
  await Image.findById(ctx.params.imageid)
  .then((image) => Comment.create({
    image_id:image._id,
    email:user.email,
    name:user.username,
    gravatar:md5(user.email),
    comment:ctx.request.body.comment
  }))
  .then(doc => ctx.response.redirect('/images/' + doc.image_id + '#' + doc._id))
  .catch(err => ctx.throw(500, err))
})

router.post('/', uploader.single('file'), async function (ctx, next) {
    let user = ctx.currentUser
    let file = ctx.req.file
    let diskFilename = file.filename + path.extname(file.originalname)
    console.log(user.username);
    await rename(file.path, path.dirname(file.path) + '/' + diskFilename)
        .then(() => Image.create({
            title: ctx.req.body.title,
            description: ctx.req.body.description,
            filename: diskFilename,
            mimetype: ctx.req.file.mimetype,
            originalname: ctx.req.file.originalname,
            userName: user.username
        }))
        .then(doc => ctx.response.redirect('/images/' + doc.id))
        .catch(err => ctx.throw(500, err))
})

router.get('/:imageid', async function(ctx, next) {

  let image = await Image.findById(ctx.params.imageid)
  image.views = image.views + 1
  await image.save()

  await Promise.all([
      stats(),
      popular(),
      comments(),
      Comment.find({ image_id: ctx.params.imageid })
  ])
  .then(([stats, pImages, comments, docs]) => ctx.render('image',
      {image, stats, pImages, comments, uComments: docs}
  ))
  .catch(err => ctx.throw(500, err))
})


router.delete('/:imageid', async function (ctx, next) {
  let user = ctx.currentUser;
  let image = await Image.findById(ctx.params.imageid)
  if(user.type == 1 || image.userName == user.username) {
    await unlink(path.resolve('./public/upload/' + image.filename))
    .then(() => Image.deleteOne({_id : ctx.params.imageid}))
    .then(() => Comment.deleteMany({image_id : ctx.params.imageid}))
    .then(() => ctx.body = { res: true })
    .catch(err => ctx.throw(500, err))
  } else {
    ctx.body = { res: false }
  }
})

router.post('/:imageid/like', async function (ctx, next) {
  let tImage
  await Image.findById(ctx.params.imageid)
  .then(image => {
    image.likes = image.likes + 1
    image.save()
    tImage = image
  })
  .then(image => ctx.body = { likes: tImage.likes })
  .catch(err => ctx.throw(500, err))
})


module.exports = router
